package com.blb.service.impl;

import com.blb.mapper.NewsDao;
import com.blb.pojo.BranchEnterprise;
import com.blb.pojo.News;
import com.blb.service.NewsService;
import com.blb.util.Page;
import com.blb.util.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author 祖星毅
 */
@Service
public class NewsServiceImpl implements NewsService {
    @Autowired
    private NewsDao newsDao;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 分页查找新闻表
     * @param page
     * @param size
     * @return
     */
    @Override
    public Page selectByPage(Integer page, Integer size) {
        String key = "News"+page+""+size;
        ValueOperations<String, Page> operations = redisTemplate.opsForValue();
        //判断redis中是否有键为key的缓存
        Boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey){
            System.out.println("缓存获取数据");
            return operations.get(key);
        }else {
            List<News> news1 = newsDao.selectByPage((page - 1) * size, size);
            List<News> news = newsDao.selectByPage(0, 0);
            Page page1 = PageUtil.page(news1, news, page, size);
            //写入缓存
            operations.set(key,page1,1, TimeUnit.MINUTES);
            return page1;
        }
    }

    /**
     * 新闻表通过主键id查找
     * @param newsId
     * @return
     */
    @Override
    public News selectByPrimaryKey(Integer newsId) {
        String key = "NewsByKey"+newsId;
        ValueOperations<String, News> operations = redisTemplate.opsForValue();
        //判断redis中是否有键为key的缓存
        Boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey){
            System.out.println("缓存获取数据");
            return operations.get(key);
        }else {
            News news = newsDao.selectByPrimaryKey(newsId);
            //写入缓存
            operations.set(key,news,1, TimeUnit.MINUTES);
            return news;
        }
    }


}
